<?php
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;

class LoginController extends Controller
{
    public function __construct()
    {
    }

    //登录
    public function dologin(Request $request)
    {
        $arys = $request->all();
        $name = isset($arys['name'])&&$arys['name'] ? $arys['name'] : '';
        $pwd = isset($arys['pwd'])&&$arys['pwd'] ? $arys['pwd'] : '';
        if (!$name || !$pwd) {
            return $this->toJson(-2,'账号、密码必填');
        }
        $file = file_get_contents('dhadmin.json');
        if (!$file) {
            return $this->toJson(-2,'没有管理员');
        }
        $adminOne = json_decode($file,true);
        if ($adminOne['uname']!=$name) {
            return $this->toJson(-2,'账号不存在');
        }
        if ($adminOne['upwd']!=md5($pwd)) {
            return $this->toJson(-2,'密码错误');
        }
        //设置session
        $adminInfo = [
            'adminid'=>$adminOne['id'],
            'adminName'=>$adminOne['uname'],
        ];
        app('session')->put('adminInfo',$adminInfo);
        return $this->toJson(0,'success',$adminInfo);
    }

    //获取session
    public function getAdminInfo(Request $request)
    {
        $adminInfo = app('session')->get('adminInfo');
        return $this->toJson(0,'success',$adminInfo);
    }

    //修改账号密码
    public function setAdmin(Request $request)
    {
        $arys = $request->all();
        $name = isset($arys['name'])&&$arys['name'] ? $arys['name'] : '';
        $pwd = isset($arys['pwd'])&&$arys['pwd'] ? $arys['pwd'] : '';
        $pwd2 = isset($arys['pwd2'])&&$arys['pwd2'] ? $arys['pwd2'] : '';
        if (!$name || !$pwd) {
            return $this->toJson(-2,'账号、密码必填');
        }
//        if ($pwd==$pwd2) {
//            return $this->toJson(-2,'老密码、新密码同一个');
//        }
        $file = file_get_contents('dhadmin.json');
        if (!$file) {
            return $this->toJson(-2,'没有管理员');
        }
        $adminOne = json_decode($file,true);
        if ($adminOne['uname']!=$name) {
            return $this->toJson(-2,'账号不存在');
        }
//        if ($adminOne['upwd']!=md5($pwd)) {
//            return $this->toJson(-2,'原密码错误');
//        }
        $adminInfo = [
            'cn'=>'管理员', 'id'=>1,
            'uname'=>$name, 'upwd'=>md5($pwd2),
        ];
        $json = json_encode($adminInfo,384);
        file_put_contents('dhadmin.json',$json);
        return $this->toJson(0);
    }
}